let map = null
let allCustomPolygon = []
let currentRegionCode = '' // 存储当前鼠标所在区域的code
let currentRegionName = '' // 存储当前鼠标所在区域的名称
let regionChildInfo = []
let allPolyline = []
let intCode = "140000000000"

function addPolygon(data, name, line, lineOpacity, area, areaOpacity, isSetFitView, parentName) {
    // 检查该名称是否已经渲染过
    if (allPolyline.some(item => item.name === name)) {
        return;
    }
    // 创建Polyline对象，用于绘制线
    let polyline = new AMap.Polygon({
        path: data, // 设置路径为解析后的点数组
        strokeColor: line,
        strokeOpacity: lineOpacity,
        strokeWeight: 5,
        strokeStyle: 'dashed',
        fillColor: area,
        fillOpacity: areaOpacity,
        extData: {name: name} // 存储区域名称
    });
    polyline.setMap(map);
    allCustomPolygon.push(polyline)
    if (isSetFitView) {
        setFitViewToMap()
    } else {
        const obj = {
            name: name,
            parentName: parentName,
            polyline: polyline,
        }
        allPolyline.push(obj)
    }
    // 获取路径的中心点（用于显示地区名称）
    let centerPoint = polyline.getBounds().getCenter();
    // 创建文本标注
    let text = new AMap.Text({
        text: name, // 要显示的地区名称
        position: centerPoint, // 设置文本标注的位置为路径的中心点
        map: map, // 指定要显示的地图
        style: {
            backgroundColor: 'transparent', // 背景透明
            border: 'none', // 无边框
            fontSize: '18px', // 字体大小
            color: 'rgba(255,0,30,0.9)', // 文字颜色
            textAlign: 'center'
        },
        zooms: [map.getZoom(), 20]
    });
    // 将文本标注添加到地图
    text.setMap(map);

    // 添加鼠标移入事件
    polyline.on('mouseover', function () {
        if (name !== currentRegionName) {
            currentRegionName = name;
            // 获取该区域的code
            const region = regionChildInfo.find(item => item.name === name);
            if (region && region.code) {
                currentRegionCode = region.code;
            }
        }
    });

    // 添加点击事件
    polyline.on('click', function () {
        const region = regionChildInfo.find(item => item.name === name);
        if (region && region.code) {
            const parentPolyline = allPolyline.find(item => item.parentName === name || item.name === name);
            if (parentPolyline) {
                const toRemove = [];
                allPolyline.forEach((item, index) => {
                    if (item.parentName === name || item.name === name) {
                        item.polyline.setMap(null);
                        toRemove.unshift(index); // 反向插入以便正确删除
                    }
                });
                toRemove.forEach(index => allPolyline.splice(index, 1));
            } else {
                // 调用getMapData获取新的区域数据
                getMapData(region.code, name, false);
            }
        }
    });
}

function setFitViewToMap() {
    if (allCustomPolygon.length > 0) {
        map.setFitView(allCustomPolygon, false, [60, 250, 0, 0])
    }
}

var center = ''
$(function () {
    var code = getQueryString('code')
    intCode = code;
    center = getQueryString('center')
    var zoom = getQueryString('zoom')
    getLeftData()
    getMapData(code, null, true)
    getHallList()
    initMap(center, zoom)
})

function initMap(center, zoom) {
    map = new AMap.Map("map", {
        center: center ? JSON.parse(center) : [112.978606, 36.867027],
        zoom: zoom ? zoom : 11,
        mapStyle: "amap://styles/normal",
        features: ["bg", "road", "building", "point"],
    });
}

// 单按钮主题切换功能
document.getElementById("theme-btn").addEventListener("click", function () {
    if (!map) return;

    const btn = this;
    if (btn.textContent === "切换暗色") {
        map.setMapStyle("amap://styles/dark");
        btn.textContent = "切换亮色";
        btn.classList.add("dark");
    } else {
        map.setMapStyle("amap://styles/normal");
        btn.textContent = "切换暗色";
        btn.classList.remove("dark");
    }
});

var hallList = []
var lngLatArray = []
var markList = []
var lastMarkList = []
var textList = []
var lastTextList = []
var newData = []

function getHallList() {
    markList = []
    textList = []
    lastMarkList = []
    lastTextList = []
    $.ajax({
        url: url + "/api/government/info/list",
        type: "get",
        data: {usePage: '0'},
        headers: headers,
        success: function (data) {
            if (data.success) {
                hallList = data.data.filter(item => item.hallPosition && item.hallPosition.length > 0)
                newData = hallList
                setMarkerData(hallList, 1)
            }
        }
    })
}

function setMarkerData(data, index) {
    data.forEach((item, index) => {
        lngLatArray.push(item.hallPosition.split(/[，,]/).map(Number))
        let lngLat = item.hallPosition.split(/[，,]/).map(Number);
        let content = `
              <p style="margin: 6px 0;">名称 : ${item.hallName}</p>
              <p style="margin: 6px 0;">电话 : ${item.contactNumber ? item.contactNumber : '无'} </p>
              <p style="margin: 6px 0;">位置 : ${item.positionInfo ? item.positionInfo : '无'} </p>`;
        const img = imgUrl + item.positionIcon + "&imgType=2"
        if (index === data.length - 1) {
            checkDimensionImg(lngLat, img, content, item.simpleName, "hall", 'last')
        } else {
            checkDimensionImg(lngLat, img, content, item.simpleName, "hall", '')
        }
    })

    if (index === 1 && lngLatArray.length > 0) {
        let sumLng = 0, sumLat = 0;
        lngLatArray.forEach(lngLat => {
            sumLng += lngLat[0];
            sumLat += lngLat[1];
        });
        let avgLng = (sumLng / lngLatArray.length).toFixed(6);
        let avgLat = (sumLat / lngLatArray.length).toFixed(6);
        var initPos = [parseFloat(avgLng), parseFloat(avgLat)];
        // 定位到所有大厅的中心点
        if (!center) {
            moveToLocation(initPos[0], initPos[1], 11)
        }

    }

}

function moveOtherToLocation(lat, zoom) {
    delMarker()
    lastMarkList = []
    lastTextList = []
    let lngLat = lat.split(',').map(Number);
    setMapZoom(zoom);
    map.setCenter(lngLat);
    removeInfoWindows()
    lastMarkList = markList.filter((item) => {
        if (item._position.join(',') !== lat) {
            return item
        }
    })
    lastTextList = textList.filter((item) => {
        if (item._position.join(',') !== lat) {
            return item
        }
    })
    var newData = hallList.filter(item => item.hallPosition === lat)
    let content = `
              <p style="margin: 6px 0;">名称 : ${newData[0].hallName}</p>
              <p style="margin: 6px 0;">电话 : ${newData[0].contactNumber} </p>
              <p style="margin: 6px 0;">位置 : ${newData[0].positionInfo} </p>`;
    const img = imgUrl + newData[0].positionIcon + "&imgType=2"
    checkSpecDimensionImg(lngLat, img, content, newData[0].simpleName, "hall", 'last')
}

async function checkDimensionImg(lngLat, image, content, text, type, isLast) {
    try {
        // 创建新的弹性标记点
        const aspectRatio = await loadImageSize(image);
        const height1 = 5;
        const height2 = 20;
        const width1 = height1 * aspectRatio;
        const width2 = height2 * aspectRatio;
        let size1 = [width1, height1];
        let size2 = [width2, height2];

        var marker = new AMap.ElasticMarker({
            position: lngLat,
            styles: [
                {
                    icon: {
                        img: image,
                        size: size1,
                        anchor: 'bottom-center',
                        fitZoom: 8,
                        scaleFactor: 2,
                        maxScale: 2,
                        minScale: 1,
                    },
                },
                {
                    icon: {
                        img: image,
                        size: size2,
                        anchor: 'bottom-center',
                        fitZoom: 10,
                        scaleFactor: 2,
                        maxScale: 3,
                        minScale: 1,
                    },
                },
            ],
            zoomStyleMapping: {
                1: 0, 2: 0, 3: 0, 4: 0, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1,
                10: 1, 11: 1, 12: 1, 13: 1, 14: 1, 15: 1, 16: 1, 17: 1, 18: 1, 19: 1, 20: 1
            },
        });

        // 确保marker被添加到地图上
        marker.setMap(map);
        markList.push(marker);

        if (text) {
            var textMarker = new AMap.Text({
                position: lngLat,
                text: text,
                anchor: 'center',
                offset: new AMap.Pixel(0, -65),
                style: {
                    backgroundColor: 'transparent',
                    border: 'none',
                    color: '#666',
                    fontSize: '14px',
                    fontWeight: '400',
                },
                zooms: [11.42, 20]
            });
            textMarker.setMap(map);
            textList.push(textMarker);
        }

        if (isLast === 'last') {
            lastMarkList = [...markList];
            lastTextList = [...textList];
            setMarker();
        }

        marker.on('click', (e) => {
            const lngLat = e.lnglat;
            showInfoWindow(lngLat, content);
        });

        return marker;
    } catch (error) {
        console.error('创建标记失败:', error);
        return null;
    }
}

async function checkSpecDimensionImg(lngLat, image, content, text, type, isLast) {
// 创建新的弹性标记点
    const aspectRatio = await loadImageSize(image);
    const height1 = 10;
    const height2 = 30;
    const width1 = height1 * aspectRatio;
    const width2 = height2 * aspectRatio;
    let size1 = [width1, height1];
    let size2 = [width2, height2];
    var marker = new AMap.ElasticMarker({
        position: lngLat,
        styles: [
            {
                icon: {
                    img: image,
                    size: size1,//可见区域的大小
                    anchor: 'bottom-center',//锚点
                    fitZoom: 8,//最合适的级别
                    scaleFactor: 2,     // 放大一级时缩放比例
                    maxScale: 2,        // 最大放大比例
                    minScale: 1,         // 最小缩放比例
                },
            },
            {
                icon: {
                    img: image,
                    size: size2,//可见区域的大小
                    anchor: 'bottom-center',//锚点
                    fitZoom: 10,//最合适的级别
                    scaleFactor: 2,   // 放大一级时缩放比例
                    maxScale: 3,      // 最大放大比例
                    minScale: 1,     // 最小缩放比例
                },
            },
        ],
        zoomStyleMapping: {
            1: 0, 2: 0, 3: 0, 4: 0, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1,
            10: 1, 11: 1, 12: 1, 13: 1, 14: 1, 15: 1, 16: 1, 17: 1, 18: 1, 19: 1, 20: 1
        },
    });
    // marker.setMap(map)
    lastMarkList.push(marker)

    // map.add(markList);
    if (text) {
        // 在 ElasticMarker 的位置上创建文本标注
        var text = new AMap.Text({
            position: lngLat,
            text: text,  // 这里是你想要显示的标注名字
            anchor: 'center', // 锚点居中
            offset: new AMap.Pixel(0, -94), // 向上偏移，确保文字在图标上方
            style: {
                backgroundColor: 'transparent', // 设置背景透明
                border: 'none', // 去掉边框
                color: '#000',  // 文字颜色
                fontSize: '18px', // 文字大小
                fontWeight: 'bold', // 加粗文字
            },
            zooms: [11.42, 20]
        });
        lastTextList.push(text)
        // map.add(text);
    }
    if (isLast === 'last') {
        setMarker()
    }
    marker.on('click', (e) => {
        const lngLat = e.lnglat;
        showInfoWindow(lngLat, content);
    });
    // this.markersLngLats.push(marker)
}

function setMarker() {
    // 清除之前的标记
    delMarker();

    // 重新添加所有标记
    lastMarkList.forEach(marker => {
        if (marker && !marker.getMap()) {
            marker.setMap(map);
        }
    });

    lastTextList.forEach(text => {
        if (text && !text.getMap()) {
            text.setMap(map);
        }
    });
}

function delMarker() {
    if (lastMarkList && lastMarkList.length > 0) {
        lastMarkList.forEach(marker => {
            if (marker && marker.getMap()) {
                marker.setMap(null);
            }
        });
    }

    if (lastTextList && lastTextList.length > 0) {
        lastTextList.forEach(text => {
            if (text && text.getMap()) {
                text.setMap(null);
            }
        });
    }
}

// 动态计算图标的宽度
function loadImageSize(url) {
    return new Promise((resolve) => {
        const img = new Image();
        img.src = url;
        img.onload = () => {
            const aspectRatio = img.width / img.height;
            resolve(aspectRatio);
        };
    });
}

function moveToLocation(latitude, longitude, zoom) {
    setMapZoom(zoom);
    map.setCenter([latitude, longitude]);
    removeInfoWindows()
}

// function moveOtherToLocation(lat,zoom){
//     let lngLat = lat.split(',').map(Number);
//     setMapZoom(zoom);
//     map.setCenter(lngLat);
//     removeInfoWindows()
// }
var infoWindows = []

function removeInfoWindows() {
    infoWindows.forEach(infoWindow => {
        infoWindow.remove()
    })
}

// 点击显示自定义内容
function showInfoWindow(lnglat, content) {
    // 创建信息窗体
    let infoWindow = new AMap.InfoWindow({
        content: content,
        offset: new AMap.Pixel(0, -30)
    });
    // 设置信息窗体的位置
    infoWindow.setPosition(lnglat);
    // 显示信息窗体
    infoWindow.open(map);
    infoWindows.push(infoWindow)
}

function setMapZoom(zoom) {
    map.setZoom(zoom);
}

function getMapData(code, parentName, isSetFitView) {
    let nameBox = document.getElementById("nameBox"); //区县级
    $.ajax({
        url: url + "/api/government/info/boundaries/list",
        type: "get",
        data: {regionCode: code},
        headers: headers,
        success: function (data) {
            if (data && data.success && data.data) {
                // 确保regionChildInfo存在且是数组
                if (data.data.regionChildInfo && Array.isArray(data.data.regionChildInfo)) {
                    regionChildInfo.push(...data.data.regionChildInfo);

                    data.data.regionChildInfo.forEach(v => {
                        if (v.coordinates && v.coordinates.length > 0) {
                            const coordinates = JSON.parse(v.coordinates);
                            let line = v.lineColor ? v.lineColor : '#4A39F8';
                            let lineOpacity = v.lineOpacity ? Number(v.lineOpacity) / 100 : 0.8;
                            let area = v.areaColor ? v.areaColor : '#000000';
                            let areaOpacity = v.areaOpacity ? Number(v.areaOpacity) / 100 : 0.2;
                            addPolygon(coordinates, v.name, line, lineOpacity, area, areaOpacity, isSetFitView, parentName);
                        }
                    });
                }

                if (intCode !== "140000000000") {
                    nameBox.innerHTML = data.data.regionInfo ? data.data.regionInfo.name : '';
                }

            } else {
                console.error('获取区域数据失败:', data);
            }
        },
        error: function (xhr, status, error) {
            console.error('请求区域数据出错:', error);
        }
    });
}

function getLeftData() {
    let countyNum = document.getElementById("countyNum"); //区县级
    let townNum = document.getElementById("townNum"); //乡镇级
    let villageNum = document.getElementById("villageNum"); //社区级
    let terminalNum = document.getElementById("terminalNum"); //自助终端
    let searchListContainer = document.getElementById("searchList"); //列表数据盒子
    $.ajax({
        url: url + "/api/government/info/getAllRegionCount",
        type: "get",
        headers: headers,
        success: function (data) {
            if (data.success) {
                var str = ''
                valueFlash(countyNum, data.data.xianCount, 1);
                valueFlash(townNum, data.data.jieCount, 1);
                valueFlash(villageNum, data.data.cunCount, 1);
                valueFlash(terminalNum, data.data.terminalCount, 1);
                data.data.hotData.forEach(function (item, index) {
                    str += '<li >' +
                        '<div class="list-left-box">' +
                        '<div class="list-left-title" onclick="turnDetail(\'' + item.id + '\')">' + item.hallName + '</div>' +
                        '<div class="map-content-box">' +
                        '<img src="images/goverMap/map-pin.png" alt="">' +
                        '<div>' + item.positionInfo + '</div>' +
                        '</div>' +
                        '</div>' +
                        '<div class="list-to-box" onclick="moveOtherToLocation(\'' + item.hallPosition + '\',16)">' +
                        '<img src="images/goverMap/to-map.png" alt="">' +
                        '<div>到这里</div>' +
                        '</div>' +
                        '</li>'
                })
                searchListContainer.innerHTML = str;
            }

        },
    });
}

var isFirst = true

function turnDetail(id) {
    let maskTitle = document.getElementById("maskTitle"); //标题
    let maskPhone = document.getElementById("maskPhone"); //电话
    let maskTime = document.getElementById("maskTime"); //时间
    let maskDetail = document.getElementById("maskDetail");
    let maskBox = document.getElementById("maskBox");
    let slideImgButton = document.getElementById("slideImg");
    let floorImgButton = document.getElementById("floorImg");
    let slideImgBox = document.getElementById("slideImgSwiper");
    let floorImgBox = document.getElementById("floorImgSwiper");
    let specDetail = document.getElementById("specDetail");
    $.ajax({
        url: url + "/api/government/info/searchList",
        type: "get",
        headers: headers,
        data: {
            id: id,
            usePage: '0',
        },
        success: function (data) {
            if (data.success) {
                maskTitle.innerHTML = data.data[0].hallName;
                maskPhone.innerHTML = data.data[0].contactNumber;
                maskTime.innerHTML = data.data[0].workTime.replace(/\n/g, '<br/>');
                maskDetail.innerHTML = data.data[0].positionInfo;
                specDetail.classList.remove('map-spec-detail')
                if (data.data[0].hallFilePathList.length > 0 && data.data[0].floorFilePathList.length > 0) {
                    slideImgButton.style.display = 'block'
                    slideImgBox.style.display = 'block'
                    floorImgBox.style.display = 'none'
                    slideImgButton.classList.add('detail-checked')
                    floorImgButton.classList.remove('detail-checked')
                    floorImgButton.style.display = 'block'
                    setSlideImg(data.data[0].hallFilePathList)
                    setFloorImg(data.data[0].floorFilePathList)
                    isFirst = true
                } else if (data.data[0].hallFilePathList.length > 0 && data.data[0].floorFilePathList.length <= 0) {
                    slideImgButton.style.display = 'block'
                    slideImgBox.style.display = 'block'
                    floorImgBox.style.display = 'none'
                    slideImgButton.classList.add('detail-checked')
                    floorImgButton.classList.remove('detail-checked')
                    floorImgButton.style.display = 'none'
                    setSlideImg(data.data[0].hallFilePathList)
                    isFirst = true
                } else if (data.data[0].hallFilePathList.length <= 0 && data.data[0].floorFilePathList.length > 0) {
                    setFloorImg(data.data[0].floorFilePathList, 1)
                    slideImgButton.style.display = 'none'
                    floorImgBox.style.display = 'block'
                    slideImgBox.style.display = 'none'
                    floorImgButton.classList.add('detail-checked')
                    slideImgButton.classList.remove('detail-checked')
                    floorImgButton.style.display = 'block'
                    isFirst = false
                } else {
                    slideImgButton.style.display = 'none'
                    floorImgButton.style.display = 'none'
                    slideImgBox.style.display = 'none'
                    floorImgBox.style.display = 'none'
                    specDetail.classList.add('map-spec-detail')
                }
                maskBox.style.display = 'flex'
            }

        },
    });
}

var slideSwiper = ''
var floorSwiper = ''
var allSwiper = ''
var slideLength = 0
var floorLength = 0
var isOpenFloor = false

function setSlideImg(imgList) {
    slideLength = imgList.length
    let slideImgBox = document.getElementById("slideImgBox");
    var str = ''
    //
    imgList.forEach((item, index) => {
        str += '<div class="swiper-slide ">' +
            '<img class="slideImg" src="' + imgUrl + item + '+&imgType=2" data-index="' + index + '" onclick="showImg(this)"  />' +
            '</div>'
    })
    slideImgBox.innerHTML = str
    if (slideLength > 2) {
        slideSwiper = new Swiper('.swiper-container-one', {
            loop: false,
            navigation: {
                nextEl: ".swiper-next-one",
                prevEl: ".swiper-prev-one",
            },
            slidesPerView: 2,
            observer: true,
            initialSlide: 0,
            resistanceRatio: 0.4,
            allowSwipeToNext: true,
            allowSwipeToPrev: true
        });
        slideSwiper.allowTouchMove = false;
    }

}

function setFloorImg(imgList, index) {
    floorLength = imgList.length
    let floorImgBox = document.getElementById("floorImgBox");
    var str = ''
    imgList.forEach((item, index) => {
        str += '<div class="swiper-slide">' +
            '<img class="floorImg" src="' + imgUrl + item + '+&imgType=2" data-index="' + index + '" onclick="showImg(this)" />' +
            '</div>'
    })
    floorImgBox.innerHTML = str
    if (index === 1 && floorLength > 2) {
        isOpenFloor = true
        floorSwiper = new Swiper('.swiper-container-two', {
            navigation: {
                nextEl: ".swiper-next-two",
                prevEl: ".swiper-prev-two",
            },
            slidesPerView: 2,
            observer: true,
            initialSlide: 0,
            resistanceRatio: 0.4,
            allowSwipeToNext: true,
            allowSwipeToPrev: true
        });
        floorSwiper.allowTouchMove = false;
    }

}

function showImg(e) {
    let maskImgBox = document.getElementById("maskImgBox");
    maskImgBox.style.display = 'block'
    const showIndex = e.dataset.index
    let allImgBox = document.getElementById("allImgBox");
    var str = ''
    var imagesArray = []
    if (isFirst) {
        imagesArray = document.querySelectorAll('.slideImg');
    } else {
        imagesArray = document.querySelectorAll('.floorImg');
    }
    imagesArray.forEach((item) => {
        str += '<div class="swiper-slide">' +
            '<img src="' + item.src + '"/>' +
            '</div>'
    })
    allImgBox.innerHTML = str
    allSwiper = new Swiper('.swiper-container-three', {
        loop: false,
        navigation: {
            nextEl: ".swiper-next-three",
            prevEl: ".swiper-prev-three",
        },
        spaceBetween: 0,
        observer: true,
        initialSlide: Number(showIndex),
        resistanceRatio: 0.4,
        allowSwipeToNext: true,
        allowSwipeToPrev: true,
    });
    allSwiper.allowTouchMove = false;

}

function closeImg() {
    allSwiper.destroy()
    let maskImgBox = document.getElementById("maskImgBox");
    maskImgBox.style.display = 'none'
}

function changeImg(index) {
    let slideImgButton = document.getElementById("slideImg");
    let floorImgButton = document.getElementById("floorImg");
    let slideImgBox = document.getElementById("slideImgSwiper");
    let floorImgBox = document.getElementById("floorImgSwiper");
    if (index === 1) {
        floorImgButton.classList.remove('detail-checked')
        slideImgButton.classList.add('detail-checked')
        slideImgBox.style.display = 'block'
        floorImgBox.style.display = 'none'
        isFirst = true
    } else {
        isFirst = false
        floorImgButton.classList.add('detail-checked')
        slideImgButton.classList.remove('detail-checked')
        slideImgBox.style.display = 'none'
        floorImgBox.style.display = 'block'
        if (floorLength > 2) {
            isOpenFloor = true
            floorSwiper = new Swiper('.swiper-container-two', {
                navigation: {
                    nextEl: ".swiper-next-two",
                    prevEl: ".swiper-prev-two",
                },
                slidesPerView: 2,
                spaceBetween: 24,
                observer: true,
                initialSlide: 0,
                resistanceRatio: 0.4,
                allowSwipeToNext: true,
                allowSwipeToPrev: true
            });
            floorSwiper.allowTouchMove = false;
        }

    }
}

function checkSpecTYpe(name, type) {
    let searchTitleContainer = document.getElementById("searchTitle"); //列表标题
    let searchListContainer = document.getElementById("searchList"); //列表数据盒子
    let noContent = document.getElementById("noContent"); //列表数据盒子
    $.ajax({
        url: url + "/api/government/info/searchList",
        type: "get",
        headers: headers,
        data: {
            positionCategory: type,
            usePage: '0',
        },
        success: function (data) {
            if (data.success) {
                var str = ''
                if (data.data.length > 0) {
                    data.data.forEach(function (item, index) {
                        str += '<li >' +
                            '<div class="list-left-box" onclick="turnDetail(\'' + item.id + '\')">' +
                            '<div class="list-left-title">' + item.hallName + '</div>' +
                            '<div class="map-content-box">' +
                            '<img src="images/goverMap/map-pin.png" alt="">' +
                            '<div>' + item.positionInfo + '</div>' +
                            '</div>' +
                            '</div>' +
                            '<div class="list-to-box" onclick="moveOtherToLocation(\'' + item.hallPosition + '\',16)">' +
                            '<img src="images/goverMap/to-map.png" alt="">' +
                            '<div>到这里</div>' +
                            '</div>' +
                            '</li>'
                    })
                    searchListContainer.style.display = 'block'
                    noContent.style.display = 'none'
                    searchListContainer.innerHTML = str;

                } else {
                    searchListContainer.style.display = 'none'
                    noContent.style.display = 'block'
                }
                searchTitleContainer.innerHTML = name;
            }

        },
    });
}

function closeMask() {
    let maskBox = document.getElementById("maskBox");
    if (slideLength > 2) {
        slideSwiper.destroy()
    }
    if (floorLength > 2 && isOpenFloor) {
        floorSwiper.destroy()
    }
    maskBox.style.display = 'none'
}

//获取地址栏参数
function getQueryString(name) {
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
    var r = window.location.search.substr(1).match(reg);
    if (r != null) {
        return decodeURI((r[2]));
    }
    return null;
}

// 搜索
function searchList() {
    var searchName = document.getElementById("searchName");
    let searchTitleContainer = document.getElementById("searchTitle"); //列表标题
    let searchListContainer = document.getElementById("searchList"); //列表数据盒子
    let noContent = document.getElementById("noContent"); //列表数据盒子
    if (searchName.value === '') {
        searchTitleContainer.innerHTML = '热门搜索'
        getLeftData()
    } else {
        $.ajax({
            url: url + "/api/government/info/searchList",
            type: "get",
            headers: headers,
            data: {
                hallName: searchName.value,
                usePage: '0',
            },
            success: function (data) {
                if (data.success) {
                    var str = ''
                    if (data.data.length > 0) {
                        data.data.forEach(function (item, index) {
                            str += '<li >' +
                                '<div class="list-left-box" onclick="turnDetail(\'' + item.id + '\')">' +
                                '<div class="list-left-title">' + item.hallName + '</div>' +
                                '<div class="map-content-box">' +
                                '<img src="images/goverMap/map-pin.png" alt="">' +
                                '<div>' + item.positionInfo + '</div>' +
                                '</div>' +
                                '</div>' +
                                '<div class="list-to-box" onclick="moveOtherToLocation(\'' + item.hallPosition + '\',16)">' +
                                '<img src="images/goverMap/to-map.png" alt="">' +
                                '<div>到这里</div>' +
                                '</div>' +
                                '</li>'
                        })
                        searchListContainer.style.display = 'block'
                        noContent.style.display = 'none'
                        searchListContainer.innerHTML = str;

                    } else {
                        searchListContainer.style.display = 'none'
                        noContent.style.display = 'block'
                    }
                    searchTitleContainer.innerHTML = '热门搜索'
                }

            },
        });
    }

}

var isOpen = true

function openClose() {
    let leftBox = document.getElementById("leftBox"); //列表数据盒子
    if (isOpen) {
        leftBox.classList.add('spec-list-box')
        isOpen = false
    } else {
        leftBox.classList.remove('spec-list-box')
        isOpen = true
    }
}

function toggleSwitch(checkbox, type) {
    if (checkbox.checked) {
        newData = newData.filter(item => item.positionCategory !== type)
        var filterData = hallList.filter(item => item.positionCategory === type)
        newData = newData.concat(filterData)
    } else {
        newData = newData.filter(item => item.positionCategory !== type)
    }
    setSpecMarker()
}

function setSpecMarker() {
    // 清除现有标记
    delMarker();
    markList = [];
    textList = [];
    lastMarkList = [];
    lastTextList = [];
    removeInfoWindows();

    // 使用Promise.all确保所有标记都创建完成
    const markerPromises = newData.map((item, index) => {
        return new Promise(async (resolve) => {
            let lngLat = item.hallPosition.split(',').map(Number);
            let content = `
                <p style="margin: 6px 0;">名称 : ${item.hallName}</p>
                <p style="margin: 6px 0;">电话 : ${item.contactNumber ? item.contactNumber : '无'} </p>
                <p style="margin: 6px 0;">位置 : ${item.positionInfo ? item.positionInfo : '无'} </p>`;
            const img = imgUrl + item.positionIcon + "&imgType=2";

            const isLast = index === newData.length - 1;
            const marker = await checkDimensionImg(lngLat, img, content, item.simpleName, "hall", isLast ? 'last' : '');
            resolve(marker);
        });
    });

    Promise.all(markerPromises).then(() => {
        console.log('所有标记创建完成');
    }).catch(error => {
        console.error('创建标记时出错:', error);
    });
}



